﻿(function() {
    $(function() {

        var _dataMigrationService = abp.services.app.dataMigration;
        var _$modal = $('#ConfigCreateModal');
        var _$form = _$modal.find('form');


        $('#RefreshButton').click(function () {
            refreshUserList();
        });

        $('.delete-config').click(function () {
            
            var configId = $(this).attr("data-config-id");
            var configName= $(this).attr('data-config-name');

            deleteConfig(configId, configName);
        });

        $('.edit-config').click(function (e) {
            var configId = $(this).attr("data-config-id");
            e.preventDefault();
            $.ajax({
                url: abp.appPath + 'DataMigration/EditConfigModal?configId=' + configId,
                type: 'POST',
                contentType: 'application/html',
                success: function (content) {
                    $('#ConfigEditModal div.modal-content').html(content);
                },
                error: function (e) { }
            });
        });

        $('.btn-addconfig').click(function (e) {
            var projectid = $(this).attr("data-config-projectid");
            var releaserecordid = $(this).attr('data-config-releaserecordid');
            _$form.find('input[name="ProjectId"]').val(projectid);
            _$form.find('input[name="ReleaseRecordId"]').val(releaserecordid);
        });

        _$form.find('button[type="submit"]').click(function (e) {
            e.preventDefault();
            if (!_$form.valid()) {
                return;
            }

            var config = _$form.serializeFormToObject(); //serializeFormToObject is defined in main.js

            //上传文件
            var resourceIds = resourceUpload();
            config.ResourceIds = resourceIds;

            abp.ui.setBusy(_$modal);
            _dataMigrationService.addConfig(config).done(function () {
                _$modal.modal('hide');
                location.reload(true); //reload page to see new user!
            }).always(function () {
                abp.ui.clearBusy(_$modal);
            });
        });

        _$modal.on('shown.bs.modal', function () {
            _$modal.find('input:not([type=hidden]):first').focus();
        });

        //初始化分页
        $.paginationInit($('.pagination'), '', 7);

        function refreshUserList() {
            location.reload(true); //reload page to see new user!
        }

        function deleteConfig(configId, configName) {
            abp.message.confirm(
                abp.utils.formatString(abp.localization.localize('AreYouSureWantToDelete', 'DevM'), configName),
                function (isConfirmed) {
                    if (isConfirmed) {
                        _dataMigrationService.deleteConfig({
                            id: configId
                        }).done(function () {
                            refreshUserList();
                        });
                    }
                }
            );
        }

        //资源操作
        _$form.find('.add-resource').click(function () {
            var template = _$form.find('.add-resource-template').html();
            var $container = _$form.find('.add-resource-container');
            var $item = $(template);
            $item.find('.btn-select-resource').on('click', function () {
                $item.find('input[type="file"]').on('change', function () {
                    $item.find('input[type="text"]').val($(this).val());
                }).click();
            });
            $item.find('.btn-remove-resource').on('click', function () {
                var _$item = $item;
                _$item.remove();
            });
            $container.append($item);
        });

        function resourceUpload() {
            var $inputs = _$form.find('.add-resource-container input[type="file"]');
            var formData = new FormData();
            $inputs.each(function () {
                formData.append('resource-' + new Date().getTime(), this.files[0]);
            });
            var ids = [];
            $.ajax({
                type: 'post'
                , url: abp.appPath + 'api/services/app/Resources/Post'
                , cache: false
                , dataType: 'JSON'
                , processData: false
                , contentType: false
                , data: formData
                , async: false
            }).done(function (res) {
                console.log(res);
                $.each(res.result.resources, function () {
                    ids.push(this.id);
                });
            });
            return ids;
        }

        //异步载入资源
        $('.panel-body-config-details').each(function () {
            var dataId = $(this).attr('data-config-id');
            var $othis = $(this);
            var $loading = $othis.find('.resource-loading');
            //abp.ui.setBusy($loading);
            _dataMigrationService.getConfigResourcesByConfigId({ id: dataId }).done(function (res) {
                var $_othis = $othis;
                if (res.length > 0) {
                    var template = $('#resource-templte').html();
                    var $ul = $(template);
                    var liTemplate = $ul.html();
                    $ul.html('');

                    $.each(res, function () {
                        var $li = $(liTemplate);
                        $li.on('click', function () {
                            var resourceId = $li.attr('data-resource-id');
                            window.open(abp.appPath + 'api/services/app/Resources/Get?resourceId=' + resourceId);
                        });
                        $li.attr('data-resource-id', this.id);
                        $li.find('.resource-name').text(this.name);
                        $ul.append($li);
                    });
                    $_othis.append($ul);
                }
                abp.ui.clearBusy($loading);
            });
        });


    });
})();
